package com.syq.service.impl;


import com.syq.dao.UserDao;
import com.syq.entity.User;
import com.syq.service.UserService;
import com.syq.utils.EmailUtils;
import com.syq.utils.Md5;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package com.qf.service.impl
 * @description: ${TODO}
 * @date 2022/6/22 14:04
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {


    private static UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
        System.out.println(userDao);
    }

    @Override
    public boolean selectByUserName(String username) {
        User user=userDao.selectByUserName(username);
        if(user!=null){
            return true;
        }
        return false;
    }

    @Override
    public void regist(@NotNull User user) {
        //1密码加密
        user.setPassword(Md5.md5(user.getPassword()));
        //2验证用户名是否可用
        User u = userDao.selectByUserName(user.getUsername());
        if(u!=null){
            throw new RuntimeException("用户名已被占用");
        }
        //3调用dao
        userDao.insert(user);
        //4发送邮件
        EmailUtils.sendEmail(user);
    }

    @Override
    public User login(String username, String password) {
        password=Md5.md5(password);
        User user=userDao.select(username,password);
        if(user==null){
            throw new RuntimeException("用户名或密码错误");
        }
        if(user.getFlag()!=1){
            throw new RuntimeException("账号未激活或已失效");
        }
        return user;
    }

    @Override
    public List<User> selectAll() {
        return userDao.selectAll();
    }
}
